package com.ben.xinyue.seckill.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ben.xinyue.seckill.domain.entity.MiaoshaOrder;
import com.ben.xinyue.seckill.domain.entity.MiaoshaUser;
import com.ben.xinyue.seckill.domain.entity.OrderInfo;
import com.ben.xinyue.seckill.domain.vo.GoodsVo;
import com.ben.xinyue.seckill.mapper.MiaoshaOrderMapper;
import com.ben.xinyue.seckill.mapper.OrderInfoMapper;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderInfoService  {

    private final OrderInfoMapper orderInfoMapper;
    private final MiaoshaOrderMapper miaoshaOrderMapper;
    private final RedissonClient redissonClient;

    /**
     * 新增订单
     * @param user 用户
     * @param goodsVo 商品
     * @return 结果
     */
    public OrderInfo createOrder(MiaoshaUser user, GoodsVo goodsVo) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goodsVo.getId());
        orderInfo.setGoodsName(goodsVo.getGoodsName());
        orderInfo.setGoodsPrice(goodsVo.getMiaoshaPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderInfoMapper.insert(orderInfo);
        MiaoshaOrder miaoshaOrder = new MiaoshaOrder();
        miaoshaOrder.setGoodsId(goodsVo.getId());
        miaoshaOrder.setOrderId(orderInfo.getId());
        miaoshaOrder.setUserId(user.getId());
        miaoshaOrderMapper.insert(miaoshaOrder);
        redissonClient.getBucket("seckill-uid-gid"+user.getId()+goodsVo.getId()).set(miaoshaOrder);
        return orderInfo;
    }


    public OrderInfo getOrderById(long orderId) {
        return orderInfoMapper.selectById(orderId);
    }


    public MiaoshaOrder getMiaoshaOrderByUserIdGoodsId(Long userId, long goodsId) {
        return (MiaoshaOrder) redissonClient.getBucket("seckill-uid-gid"+userId+goodsId).get();
    }

    public List<MiaoshaOrder> getAllMiaoshaOrdersByGoodsId(long goodsId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("goods_id",goodsId);
        return miaoshaOrderMapper.selectList(qw);
    }
}